<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Adv;

class AdvController extends Controller
{
    public function index()
    {
        $adv = Adv::all();
        return view('admin.adv.index', ['adv' => $adv]);
    }

    public function add($id = 0)
    {
        $data = [];
        if ($id > 0) {
            $data = Adv::find($id);
        }
        return view('admin.adv.add', ['data' => $data]);
    }

    public function save(Request $request)
    {
        $this->validate($request, [
            'name' => 'required'
        ], [
            'name.required' => '名称不能为空'
        ]);

        $data = $request->all();

        if (isset($data['id'])) {
            $id = $data['id'];
            unset($data['id']);
            unset($data['_token']);
            $res = Adv::where('id', $id)->update($data);
            $type = $res ? "message" : "tip";
            $message = $res ? "修改成功" : "修改失败";
            return redirect('admin/adv')->with($type, $message);
        }

        $re = Adv::create($data);
        if ($re) {
            return redirect('adv')->with('message', '添加成功');
        } else {
            return redirect('admin/adv/add')->with('tip', '添加失败');
        }
    }

    public function delete($id)
    {
        $content = Adv::find($id);

        if (!$content) {
            return response()->json(['code' => 0, 'msg' => '删除失败，记录不存在。']);
        }

        // 假设 `Adv` 模型没有 `advid` 字段，这里应该检查的是相关广告内容的存在
        if (Adv::where('cid', '=', $id)->exists()) {
            return response()->json(['code' => 0, 'msg' => '该广告位下有广告记录，请先删除广告内容。']);
        }

        $content->delete();

        return response()->json(['code' => 1, 'msg' => '删除成功']);
    }
}
